﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using myDBConnection = System.Data.SqlClient.SqlConnection;
using myDBTransaction = System.Data.SqlClient.SqlTransaction;
using YNCNumberSys.db;
using cadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using YNCNumberSys.DbDal;
using YNCNumberSys.Entity;
using static Autodesk.AutoCAD.Windows.OpenFileDialog;
using System.IO;
using common;
using AppUCtrol;

namespace YNCNumberSys
{
    public partial class PaperManagementForm : Form
    {
       // FilterRow m_fr = null;
        private string _用户名;
        public string s_用户名
        {
            get { return _用户名; }
            set{_用户名 = value;}
        }
        private void initComJCXH()
        {
            CodeDal codedal = new CodeDal();
            CodeEntity codeentity = codedal.GetCodeEntity();
            PaperCodeDal dal = new PaperCodeDal();
            PaperCodeEntity ent = new PaperCodeEntity();
            ent.Wx = null;
            ent.Zf = null;
            DataTable dt = dal.GetPaperCode(ent, codeentity);
            DataView dataView = dt.DefaultView;
            System.Data.DataTable dt_distinct = dataView.ToTable(true, "机床型号");//注：其中ToTable（）的第一个参数为是否DISTINCT
            cbx_机床型号.DisplayMember = "机床型号";
            var dr = dt_distinct.NewRow();
            dr["机床型号"] = "";
            dt_distinct.Rows.InsertAt(dr, 0);
            cbx_机床型号.DataSource = dt_distinct;
            cbx_机床型号.SelectedIndex = -1;

            string filePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string file = Path.Combine(Path.GetDirectoryName(filePath), "config.ini");
            //string file = Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, "config.ini");
            //string file = Path.Combine(System.Windows.Forms.Application.StartupPath, "config.ini");
            if (File.Exists(file))
            {
                FileIni t = new FileIni(file);
                string regKey = t.ReadValue("配置", "查询机床型号");
                if (!string.IsNullOrEmpty(regKey))
                {
                    cbx_机床型号.Text = regKey;
                }
            }
        }
        public PaperManagementForm()
        {
            InitializeComponent();
            //initComJCXH();
            //InitTree();
        }
        private void QuerybuidTree()
        {
            m_flex.BeginUpdate();
            m_flex.DataSource = null;
            m_flex.Rows.Count = 1;
            m_flex.Cols.Count = 3;
            m_flex.EndUpdate();
            m_tree.Nodes.Clear();
            CodeDal codedal = new CodeDal();
            CodeEntity codeentity = codedal.GetCodeEntity();
            PaperCodeDal dal = new PaperCodeDal();
            PaperCodeEntity ent = new PaperCodeEntity();
            ent.Wx = this.checkBox外协.Checked ? 1 : 0;
            ent.Zf = this.checkBox作废.Checked ? 1 : 0;
            ent.Zh = checkBoxShenqing.Checked ? _用户名 : "";
            ent.Jcxh = cbx_机床型号.Text != string.Empty ? cbx_机床型号.Text : string.Empty;
            ent.Ah = string.Empty;
            System.Data.DataTable dt = dal.GetPaperCode(ent, codeentity);
            if (dt == null) return;
            DataView dataView = dt.DefaultView;
            System.Data.DataTable dtDistinct = dataView.ToTable(true, "机床型号");
            DataRow[] drs;
            foreach (DataRow dr in dtDistinct.Rows)
            {
                TreeNode nodeT = m_tree.Nodes.Add(dr["机床型号"].ToString());
                nodeT.ImageIndex = nodeT.SelectedImageIndex = 0;
                drs = dt.Select(string.Format("机床型号='{0}'", (string)dr["机床型号"]));
                foreach (DataRow dr1 in drs)
                {
                    bool find = false;
                    foreach (TreeNode item in nodeT.Nodes)
                    {
                        if (item.Text == dr1["A号"].ToString())
                        {
                            find = true;
                            break;
                        }
                    }
                    if (!find)
                    {
                        TreeNode nodeTChild = new TreeNode(dr1["A号"].ToString());
                        nodeTChild.ImageIndex = nodeTChild.SelectedImageIndex = 1;
                        nodeT.Nodes.Add(nodeTChild);
                    }
                }
            }
        }
        private void btn_Query_Click(object sender, EventArgs e)
        {
            QuerybuidTree(); 
        }
        /// <summary>
        /// 选择树节点。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Tree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (sender == null)
                return;
            TreeNode selNode;
            if (sender is TreeView)
                selNode = ((TreeView)sender).SelectedNode;
            else
                return;
            if (selNode == null)
                return;
            m_flex.BeginUpdate();
            m_flex.DataSource = null;
            m_flex.Rows.Count = 1;
            m_flex.Cols.Count = 3;
            m_flex.EndUpdate();
            labelRow.Text = "";
            CodeDal codedal = new CodeDal();
            CodeEntity codeentity = codedal.GetCodeEntity();
            PaperCodeDal dal = new PaperCodeDal();
            PaperCodeEntity ent = new PaperCodeEntity();
            ent.Wx = this.checkBox外协.Checked ? 1 : 0;
            ent.Zf = this.checkBox作废.Checked ? 1 : 0;
            ent.Zh = checkBoxShenqing.Checked ? _用户名 : "";
            System.Data.DataTable dt;
            if (selNode.Parent == null)
            {
                ent.Jcxh = selNode.Text;
                ent.Ah = string.Empty;
                dt = dal.GetPaperCode(ent, codeentity);
                if (dt == null)
                    return;
            }
            else
            {
                ent.Jcxh = selNode.Parent.Text;
                ent.Ah = selNode.Text;
                dt = dal.GetPaperCode(ent, codeentity);
                if (dt == null)
                    return;
            }
            m_flex.BeginUpdate();
            m_flex.DataSource = dt;
            if (m_flex.Cols.Contains("ID"))
                m_flex.Cols["ID"].Visible = false;
            for (int r = 1; r < m_flex.Rows.Count; r++)
            {
                m_flex[r, 0] = r;
            }
            m_flex.Cols.Frozen = 2;
            m_flex.AutoSizeRows();
            m_flex.AutoSizeCols();
            m_flex.EndUpdate();
            labelRow.Text = "符合数据库记录:"+ dt.Rows.Count;
            //if (m_fr == null)
            //    m_fr = new FilterRow(m_flex);
            //if(m_fr!=null) m_fr.Clear();
        }
        /// <summary>
        /// 初始化树控件。
        /// </summary>
        private void InitTree()
        {
            m_flex.BeginUpdate();
            m_flex.DataSource = null;
            m_flex.EndUpdate();
            m_tree.Nodes.Clear();
            //m_flex.BeginUpdate();
            CodeDal codedal = new CodeDal();
            CodeEntity codeentity = codedal.GetCodeEntity();
            PaperCodeDal dal = new PaperCodeDal();
            PaperCodeEntity ent = new PaperCodeEntity();
            ent.Wx = 0;
            ent.Zf = 0;
            ent.Zh = string.Empty;
            ent.Jcxh = string.Empty;
            ent.Ah = string.Empty;
            ent.Zh = checkBoxShenqing.Checked ? _用户名 : "";
            System.Data.DataTable dt = dal.GetPaperCode(ent, codeentity);
            if (dt == null)  return;
            DataView dataView = dt.DefaultView;
            System.Data.DataTable dtDistinct = dataView.ToTable(true, "机床型号");
            DataRow[] drs;
            foreach (DataRow dr in dtDistinct.Rows)
            {
                TreeNode nodeT = m_tree.Nodes.Add(dr["机床型号"].ToString());
                nodeT.ImageIndex = nodeT.SelectedImageIndex = 0;
                drs = dt.Select(string.Format("机床型号='{0}'", (string)dr["机床型号"]));
                foreach (DataRow dr1 in drs)
                {
                    bool find = false;
                    foreach (TreeNode item in nodeT.Nodes)
                    {
                        if (item.Text == dr1["A号"].ToString())
                        {
                            find = true;
                            break;
                        }
                    }
                    if (!find)
                    {
                        TreeNode nodeTChild = new TreeNode(dr1["A号"].ToString());
                        nodeTChild.ImageIndex = nodeTChild.SelectedImageIndex = 1;
                        nodeT.Nodes.Add(nodeTChild);
                    }
                }
            }
            //m_flex.EndUpdate();
        }

        private void btn_目录输出_Click(object sender, EventArgs e)
        {
            //if (m_fr != null)
            //{
            //    m_fr.Clear();
            //    m_fr.Visible = false;
            //}
            TreeNode selNode = m_tree.SelectedNode;
            if (selNode == null)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(@"请选择要输出目录的【A号】！");
                return;
            }
            if (selNode.Parent == null)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(@"请选择要输出目录的【机床号】！");
                return;
            }
            string jch = selNode.Parent.Text;
            string ah = selNode.Text;
            OutExcelForm outexcelform = new OutExcelForm();
            outexcelform.Jch = jch;
            outexcelform.Ah = ah;
            outexcelform.User = s_用户名;
            outexcelform.Check4C = false;
            outexcelform.OutBomExcel = true;
            outexcelform.OutBomHoldonOld = false;
            outexcelform.ShowDialog();
        }
        private void btn_图号作废_Click(object sender, EventArgs e)
        {
            m_tree.SelectedNode = null;
            string info = "共选择" + m_flex.Rows.Selected.Count.ToString() + "，确定要作废吗？";
            if (MessageBox.Show(info, "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                return;
            try
            {
                System.Collections.Generic.List<string> lstSQL = new System.Collections.Generic.List<string>();
                for (int ir = 0; ir < m_flex.Rows.Selected.Count; ir++)
                {
                    int intID = int.Parse(m_flex.Rows.Selected[ir]["ID"].ToString());
                    System.Data.DataTable dt = (System.Data.DataTable)m_flex.DataSource;
                    DataRow[] rs = dt.Select("ID=" + intID);
                    if (rs[0]["作废"].ToString() != "1")
                    {
                        //为什么要另插入一个表呢，有什么用途。屏蔽掉
                        //string sql1 = @"insert into 图号作废表(机床型号,A号,零件序号,图纸编号,名称,规格,申请人,审核人,申请日期,外协,外协单位,作废,图纸类型)" +
                        //                "values('" + rs[0]["机床型号"] + "','" + rs[0]["A号"] + "','" + rs[0]["零件序号"] + "','"
                        //                + rs[0]["图纸编号"] + "','" + rs[0]["名称"] + "','" + rs[0]["规格"] + "','" + rs[0]["申请人"] + "','" + rs[0]["审核人"] + "','" + rs[0]["申请日期"] + "'," + rs[0]["外协"] + ",'" + rs[0]["外协单位"] + "',"
                        //                + rs[0]["作废"] + ",'" + rs[0]["图纸类型"] + "');";
                        //lstSQL.Add(sql1);
                        string sql2 =string.Format("update 图纸编号表 set [申请日期]='{0}', 作废=1 where ID={1} and [申请人]='{2}'", System.DateTime.Now.ToString("yyyy-MM-dd"), intID, s_用户名);
                        lstSQL.Add(sql2);
                    }
                }
                if (lstSQL.Count > 0)
                {
                    PaperCodeDal dal = new PaperCodeDal();
                    dal.InsertZfPapercodeAndPapercode(lstSQL);
                }
            }
            catch
            {
                
            }
            finally
            {

            }
        }
        private void btn_已有目录输出_Click(object sender, EventArgs e)
        {
            //if (m_fr != null) m_fr.Clear();
            TreeNode selNode = m_tree.SelectedNode;
            if (selNode == null)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(@"请选择要输出目录的【A号】！");
                return;
            }
            if (selNode.Parent == null)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(@"请选择要输出目录的【机床号】！");
                return;
            }
            string jch = selNode.Parent.Text;
            string ah =  selNode.Text;
            OutExcelForm outexcelform = new OutExcelForm();
            outexcelform.Jch = jch;
            outexcelform.Ah = ah;
            outexcelform.User = s_用户名;
            outexcelform.Check4C = false;
            outexcelform.OutBomExcel = false;
            outexcelform.OutBomHoldonOld = true;
            outexcelform.ShowDialog();
        }

        private void PaperManagementForm_Load(object sender, EventArgs e)
        {
            //FilterRow fr = new FilterRow(m_flex);
            initComJCXH();
            InitTree();
        }

        private void PaperManagementForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            string filePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string file = Path.Combine(Path.GetDirectoryName(filePath), "config.ini");
            if (File.Exists(file))
            {
                FileIni t = new FileIni(file);
                t.WriteValue("配置", "查询机床型号", cbx_机床型号.Text);
            }
        }
    }
}
